import i18next, { i18n } from 'i18next';
import './i18n';
const Storage = storage.getDataStorage('gameStorage2');
/**
 * 关于玩家血量的一些快捷API
 */
export class HPAPI {
  #entity; //别问为什么封装，问就是x.entity不好看
  constructor(entity: GameEntity) {
    this.#entity = entity;
  }
  die() {
    this.#entity.dead = true;
    this.#entity.player?.directMessage('你已死亡');
  }
  respawn() {
    this.#entity.dead = false;
    this.#entity.player?.directMessage('你已复活');
  }
}
/**
 * 关于玩家的一些快捷API，包含穿戴装备，开镜等功能
 */
export class PlayerAPI {
  #entity;
  constructor(entity: GameEntity) {
    this.#entity = entity;
  }
  wearWeapon(weapon: string, offset: GameVector3, scale: GameVector3) {
    this.#entity.player?.addWearable({
      mesh: `mesh/${weapon}.vb` as GameModelAssets,
      bodyPart: GameBodyPart.RIGHT_HAND,
      offset: offset,
      scale: scale,
    });
  }
  wearHead(weapon: string, offset: GameVector3, scale: GameVector3) {
    this.#entity.player?.addWearable({
      mesh: `mesh/${weapon}.vb` as GameModelAssets,
      bodyPart: GameBodyPart.HEAD,
      offset: offset,
      scale: scale,
    });
  }
  wearBody(weapon: string, offset: GameVector3, scale: GameVector3) {
    this.#entity.player?.addWearable({
      mesh: `mesh/${weapon}.vb` as GameModelAssets,
      bodyPart: GameBodyPart.NECK,
      offset: offset,
      scale: scale,
    });
  }
  glass(number: number) {
    const player = this.#entity.player as GamePlayer;
    player.cameraFovY = number;
  }
  wear(
    part: GameBodyPart,
    weapon: string,
    offset: GameVector3,
    scale: GameVector3
  ) {
    const entity = this.#entity as GamePlayerEntity;
    entity.player.removeWearable(entity.player.wearables(part)[0]);
    if (part === GameBodyPart.HEAD) {
      entity.player.skinInvisible[part] = false;
    }
    this.#entity.player?.addWearable({
      mesh: `mesh/${weapon}.vb` as GameModelAssets,
      bodyPart: part,
      offset: offset,
      scale: scale,
    });
  }
}
/**
 * 关于数据存储空间的API，包含存储，读取等内容
 */
export class StorageAPI {
  entity: GameEntity;
  needSave: object;
  constructor(entity: GameEntity) {
    this.entity = entity;
    this.needSave = {
      level: 0,
      exp: 0,
      weapon: ['H416', 'M4A1', 'AK47', 'M4A1'],
      money: 0,
      useWeapons: [],
      safe: [],
      score: 0,
      bagInformation: {
        size: 0,
        capacity: 500,
      },
      scwzInformation: {
        size: 0,
        capacity: 5,
      },
      safeInformation: {
        size: 0,
        capacity: 2,
      },
      useBags: '无',
      useDG: '无',
      inGame: false,
    };
  }
  getPlayerData() {
    const data = { name: this.entity.player?.name ?? '' };
    for (const i in this.needSave) {
      Object.defineProperty(data, i, {
        get: () => this.entity[i as keyof typeof this.entity],
        enumerable: true,
        configurable: true,
      });
    }
    return data;
  }
  async savePlayer() {
    const data = this.getPlayerData();
    if (typeof this.entity.player?.userId === 'string') {
      while (true) {
        try {
          await Storage?.update(this.entity.player.userId, () => data);
          break;
        } catch (error) {
          console.error(i18next.t('save_failed_retry') + error);
          await sleep(1000);
        }
      }
    } else {
      this.entity.player?.directMessage(i18next.t('no_login_no_save'));
      return;
    }
  }

  async loadPlayer() {
    Object.assign(this.entity, this.needSave);
    if (typeof this.entity.player?.userId === 'string') {
      let data;
      while (true) {
        try {
          data = await Storage?.get(this.entity.player.userId);
          break;
        } catch (err) {
          console.error(i18next.t('load_failed_retry') + err);
          await sleep(1000);
        }
      }
      if (data) {
        Object.assign(this.entity, data.value);
        this.entity.player.directMessage(i18next.t('load_success'));
        return true;
      } else {
        this.entity.player?.directMessage(i18next.t('create_success'));
        while (true) {
          try {
            await Storage?.set(this.entity.player.userId, this.getPlayerData());
            break;
          } catch (error) {
            console.error(i18next.t('save_failed_retry') + error);
            await sleep(1000);
          }
        }
        return undefined;
      }
    } else {
      this.entity.player?.directMessage(i18next.t('no_login_no_load'));
      return undefined;
    }
  }
}
/**
 * 对列表进行格式调整的API
 */
export class itemAPI {
  /**
   * 把如['hello','hello']的列表变成['hello'*2]
   */
  static goSimpleList(list: string[]) {
    const list1: string[] = [];
    for (const index of list) {
      const found = list1.find((x) => x.startsWith(index));
      if (found) {
        list1[list1.indexOf(found)] =
          `${list1[list1.indexOf(found)].split('*')[0]}*${Number(list1[list1.indexOf(found)].split('*')[1]) + 1}`;
      } else {
        list1.push(`${index}*1`);
      }
    }
    return list1;
  }
  /**
   * 在如['hello'*2]的列表中减少项目
   */
  static splice(list: string[], spliceItem: string, spliceNumber: number) {
    const list1 = list;
    const found = list.find((x) => x.startsWith(spliceItem));

    if (found) {
      const foundNumber = Number(found.split('*')[1]);

      if (foundNumber < spliceNumber) {
        return null;
      } else if (foundNumber === spliceNumber) {
        list1.splice(list1.indexOf(found), 1);
      } else {
        list1[list1.indexOf(found)] =
          `${list1[list1.indexOf(found)].split('*')[0]}*${Number(list1[list1.indexOf(found)].split('*')[1]) - spliceNumber}`;
      }
    } else {
      return null;
    }

    return list1;
  }
  /**
   * 第一个函数的反向操作
   */
  static goComplexList(list: string[]) {
    const list1: string[] = [];
    for (const index of list) {
      for (let i = 0; i < Number(index.split('*')[1]); i++) {
        list1.push(index.split('*')[0]);
      }
    }

    return list1;
  }
}
